<?php

namespace IDock\Insurance\LIHI\Request;

use IDock\Http\RequestFormat;
use IDock\Insurance\LIHI\Request\AllLIHIRequest;
use IDock\Insurance\LIHI\Response\PolicyPaymentResponse;
use IDock\Printer\NonCar\NonCarInquirySinglePrinter;
use IDock\Visitor\PolicyPaymentVisitor;
use stdClass;

class PolicyPaymentRequest extends AllLIHIRequest
{
    public $route = 'payment/getPayUrl';

    protected $response = PolicyPaymentResponse::class;

    public $format = RequestFormat::FORM;

    protected $urlTip = '支付接口';
    /**
     * @var  PolicyPaymentVisitor $visitor
     */
    protected $visitor;

    public function generate(): array
    {
        $this->flowId = $this->visitor->argc['flowId'] ?? '';

        $this->agreementCode = $this->visitor->argc['agreementNo'] ?? '';
        $this->recordCode = $this->visitor->argc['recordCode'] ?? '';

        $data = [
            'documentNo' => $this->visitor->biInquiryNo ?: $this->visitor->ciInquiryNo,
            'callBackUrl' => '',
        ];

        return $data;
    }

    /**
     * @param array $data
     * @return string
     */
    private function sign(array $data): string
    {
        $data['KEY'] = $this->payKey;
        $data = urldecode(http_build_query($data));

        $string = urldecode($data);

        $string = strtoupper(md5($string));

        return $string;
    }

    /**
     * 订单列表
     * @return array
     */
    private function goodsList(): array
    {
        $list = [];

        if ($this->visitor->ciPolicyNo) {
            $list[] = [
                'GOODID' => $this->visitor->ciPolicyNo,
                'GOODSOURCE' => '2',
                'GOODDIRECTION' => $this->goodDirection,
                'PAYFEE' => (string)(($this->visitor->argc['ciPremium'] ?? '0') * 100),
            ];
        }

        if ($this->visitor->biPolicyNo) {
            $list[] = [
                'GOODID' => $this->visitor->biPolicyNo,
                'GOODSOURCE' => '2',
                'GOODDIRECTION' => $this->goodDirection,
                'PAYFEE' => (string)(($this->visitor->argc['biPremium'] ?? '0') * 100),
            ];
        }
        //驾意险
        if(!empty($this->visitor->nonCarInquirySingle)) foreach ($this->visitor->nonCarInquirySingle as $val){
            /**@var NonCarInquirySinglePrinter $val */
            $list[] = [
                'GOODID' => $val->inquiryNo,
                'GOODSOURCE' => '1',
                'GOODDIRECTION' => $this->goodDirection,
                'PAYFEE' => (string)round(($val->premium ?? '0') * $val->insuredNum * 100),
            ];
        }
        return $list;
    }

}
